 <template>
     <view class="container" v-if="loading">
         <u-loading-page :loading="loading"></u-loading-page>
     </view>

 	<view class="container" v-else>
 		<!-- 支付状态 -->
 		<view class="item">
 			<view class="icon">
 				<u-image width="180rpx" height="180rpx" :src="getServerStatic('/static/images/a21.png')"></u-image>
 			</view>
 			<view style="width: 100%;">
 				<view class="user-info-box">
 					<view class="user-info">
                        <view class="name">{{ orderInfo.patient_name }}</view>
                        <view class="age">{{ orderInfo.patient_sex == 1 ? '男' : '女' }} {{ orderInfo.patient_age ?? 0 }}</view>
 					</view>
 					<view class="status-box">
 						<view class="status" style="display: flex;align-items: center;" v-if="orderInfo.status == 1">
							<text>待支付：</text>
							<u-count-down :time="30 * 60 * 60 * 1000" format="HH:mm:ss"></u-count-down>
						</view>
                        <view class="done" v-if="orderInfo.status == 3">已完成</view>
                        <view class="done" v-if="orderInfo.status == 0">已取消</view>
                        <view class="status" v-if="orderInfo.status == 2">待就诊</view>
 					</view>
 				</view>
 				<view class="mobile">
                    {{ orderInfo.patient_mobile ?? '' }}
 				</view>
 			</view>
 		</view>

 		<!-- 挂号信息 -->
 		<view class="order-item">
 			<view class="status-box">
 				<view class="name">挂号信息</view>
 			</view>
 			<view class="content-box">
                <view class="content-item">
                    <text>医院：</text>
                    <text>{{ orderInfo.hospital_name ?? '' }}</text>
                </view>
                <view class="content-item">
                    <text>预约项目：</text>
                    <text>{{ orderInfo.project_name ?? '' }}</text>
                </view>
                <view class="content-item">
                    <text>医生：</text>
                    <text>{{ orderInfo.doctor_name ?? '' }}</text>
                </view>

 				<view class="content-item" >
                    <text>就诊日期：</text>
                    <text>{{ orderInfo.treatment_date ?? '' }} {{ orderInfo.treatment_time ?? '00:00:00' }}-{{ orderInfo.treatment_end_time ?? '00:00:00' }}</text>
 				</view>
				<view class="content-item">
					<text>挂号费用：</text>
					<text>{{ orderInfo.price ?? '0.00' }}元</text>
				</view>
 			</view>
 			<view class="btns-box">
 				<view class="message">请在就诊当天前往医院就诊</view>
 				<view class="">
 					 <u-button throttleTime="1000"
                               :customStyle="{height: '56rpx', letterSpacing: '.1rem'}"
                               :hairline="false" type="mini" shape="circle"
                               color="linear-gradient(315deg, #4975EC 0%, #97B3FF 100%)"
                               @click="actionPay"
                               v-if="orderInfo.status == 1"
                     >
                         去支付
                     </u-button>
 					<u-button throttleTime="1000"
                              :customStyle="{height: '56rpx', boxShadow: '0rpx 4rpx 34rpx 1rpx rgba(87,129,240,0.4)', letterSpacing: '.1rem'}"
                              :hairline="false"
                              type="mini"
                              shape="circle"
                              color="linear-gradient(315deg, #4975EC 0%, #97B3FF 100%)"
                              @click="showCancelPop"
                              v-if="orderInfo.status == 2"
                    >
                        退号
                    </u-button>
 				</view>
 			</view>
 		</view>

 		<!-- 支付信息 -->
 		<view class="order-item">
 			<view class="status-box">
 				<view class="name">支付信息</view>
 			</view>
 			<view class="content-box">
 				<view class="content-item">
 					<text>支付状态：</text>
                    <text v-if="orderInfo.status == 0">已取消</text>
                    <text v-if="orderInfo.status == 1">待支付</text>
                    <text v-if="orderInfo.status == 2">已支付</text>
                    <text v-if="orderInfo.status == 3">已支付</text>
 				</view>
 				<view class="content-item">
 					<text>支付时间：</text>
                    <text>{{ orderInfo.payment_time ?? '' }}</text>
 				</view>
                <view class="content-item">
                    <text>支付订单号：</text>
                    <text>{{ orderInfo.trade_no ?? '' }}</text>
                </view>
                <view class="content-item" style="margin-bottom: 30rpx;">
                    <text>商户订单号：</text>
                    <text>{{ orderInfo.order_no ?? '' }}</text>
                </view>

 			</view>
 		</view>

        <!-- 退号信息 -->
        <view class="order-item" v-if="orderInfo.status == 0">
            <view class="status-box">
                <view class="name">退号信息</view>
            </view>
            <view class="content-box">
                <view class="icon">
                    <u-image width="180rpx" height="180rpx" :src="getServerStatic('/static/images/a21.png')"></u-image>
                </view>
                <view class="content-item">
                    <text>退号原因：</text>
                    <text v-if="orderInfo.cancel_type == 2">{{ orderInfo.cancel_reason ?? '' }}</text>
                    <text v-if="orderInfo.cancel_type == 1">支付超时 系统自动取消</text>
                </view>
                <view class="content-item" style="margin-bottom: 30rpx;">
                    <text>申请时间：</text>
                    <text>{{ orderInfo.cancel_app_time ?? '' }}</text>
                </view>
            </view>
        </view>

 	</view>

     <!-- 选择支付方式 -->
     <u-popup closeable bgColor="transparent" :show="paymentPop" @close="paymentPop = false">
         <view class="cancel-pop">
             <view class="pop-title">支付订单</view>
             <view class="info">
                 <view>预约项目: {{orderInfo.project_name}}</view>
                 <view> {{orderInfo.doctor_name}} {{orderInfo.treatment_date}} {{orderInfo.treatment_time}}-{{orderInfo.treatment_end_time}}</view>
                 <view style="margin-bottom: 0;">就诊人：{{orderInfo.project_name}} {{orderInfo.patient_mobile}}</view>
             </view>
             <view class="pop-title">请选择支付方式：</view>
             <view class="radio-wrap">
                 <u-radio-group v-model="paymentWay" placement="column" @change="handlePaymentWayChange">
                     <view class="payment-item" @click="handleSelectPayment('wechat')">
                         <view class="left">
                             <u-image width="40rpx" height="40rpx" :src="getServerStatic('/static/images/a40.png')"></u-image>
                             <view class="pay-name">微信支付</view>
                         </view>
                         <view class="right">
                             <u-radio activeColor="#516DDB" name="wechat"></u-radio>
                         </view>
                     </view>
                     <view class="payment-item center" @click="handleSelectPayment('balance')">
                         <view class="left">
                             <u-image width="40rpx" height="40rpx" :src="getServerStatic('/static/images/a41.png')"></u-image>
                             <view class="pay-name">余额支付</view>
                             <view class="pay-tip">当前余额：{{userStore.store_balance}}元</view>
                         </view>
                         <view class="right">
                             <u-radio activeColor="#516DDB" name="balance"></u-radio>
                         </view>
                     </view>
                     <view class="payment-item" @click="handleSelectPayment('coupon')">
                         <view class="left">
                             <u-image width="40rpx" height="40rpx" :src="getServerStatic('/static/images/a42.png')"></u-image>
                             <view class="pay-name">抵扣券支付</view>
                         </view>
                         <view class="right">
                             <u-radio activeColor="#516DDB" name="coupon"></u-radio>
                         </view>
                     </view>
                 </u-radio-group>
             </view>
             <view class="btn">
                 <u-button throttleTime="1000"
                           :customStyle="{height: '86rpx', boxShadow: '0rpx 4rpx 34rpx 1rpx rgba(87,129,240,0.4)', letterSpacing: '.1rem'}"
                           :hairline="false" type="mini" shape="circle"
                           color="linear-gradient(315deg, #4975EC 0%, #97B3FF 100%)"
                           @tap="toPay(orderInfo.id)"
                 >确认</u-button>
             </view>
         </view>
     </u-popup>

     <!-- 取消订单弹窗 -->
     <u-popup closeable bgColor="transparent" :show="cancelPop" @close="cancelPop = false">
         <view class="cancel-pop">
             <view class="pop-title">取消订单</view>
             <view class="info">
                 <view>预约项目 {{orderInfo.project_name}} </view>
                 <view>{{orderInfo.doctor_name}} {{orderInfo.treatment_date}} {{orderInfo.treatment_time}}-{{orderInfo.treatment_end_time}}</view>
                 <view style="margin-bottom: 0;">就诊人：{{orderInfo.patient_name}} {{ orderInfo.patient_sex == 1 ? '男' : '女' }} {{ orderInfo.patient_mobile ?? '' }}</view>
             </view>
             <view class="pop-title">请选择退号的原因（必选）：</view>
             <view class="radio-wrap">
                 <u-radio-group v-model="radioValue" placement="column">
                     <u-radio  :customStyle="{marginBottom: '46rpx'}" v-for="(item, index) in radioList" :key="index" activeColor="#D66A44"
                               :label="item.name" :name="item.name">
                     </u-radio>
                 </u-radio-group>
             </view>
             <view class="btn">
                 <u-button throttleTime="1000" :customStyle="{height: '86rpx'}" :hairline="false" type="mini"
                           shape="circle" color="linear-gradient(315deg, #D66A44 0%, #ECBFAF 100%)"
                           @click="toCancel">确认</u-button>
             </view>
         </view>
     </u-popup>

 </template>

 <script setup>
     import {ref, reactive, readonly} from "vue"
     import {onLoad, onShow, onPullDownRefresh} from '@dcloudio/uni-app'
     import {cancelOrder, getOrderDetail, initiatePayment} from "@/api/order";
     import useUniAPi from "@/hooks/useUniAPi";
     import {useUserStore} from "@/store";
     import {getServerStatic} from "@/utils/tool";
     const { navigateTo, redirectTo, goBack, payment } = useUniAPi()

     // 用户store
     const userStore = useUserStore();

     const loading = ref(true)
     const cancelPop = ref(false)
     const radioValue = ref('')
     const radioList = ref([
         {
             name: '不想要了',
         },
         {
             name: '挂号选错/多选',
         },
         {
             name: '就诊人填错了',
         },
         {
             name: '时间选错了',
         },
         {
             name: '有跟便宜的了，不想要了/其他原因',
         },
     ])

     const showCancelPop = () => {
         cancelPop.value = true
     }

     // 订单信息
     const orderInfo = reactive({
         id: '',
         patient_name: "",
         patient_sex: "",
         patient_age: "",
         patient_mobile: "",
         hospital_name: "",
         project_name: "",
         doctor_name: "",
         treatment_date: "",
         treatment_time: "",
         treatment_end_time: "",
         price: "0.00",
         status: 0,
         payment_time: 0,
         order_no: '',
         trade_no: '',
         cancel_reason: "",
         cancel_type: 1,
         cancel_app_time: "",
     })

     const orderId = ref(0)

     onLoad((evt) => {
         console.log('订单详情', evt)
         if (evt?.orderId) {
             orderId.value = evt.orderId
             handleGetOrderDetail()
         }
     })

     onPullDownRefresh(() => {
         console.log("下拉刷新")
         handleGetOrderDetail()
     })

     const handleGetOrderDetail = async () => {
         loading.value = true;
         const {code, data, message} = await getOrderDetail({orderId: orderId.value})
         loading.value = false;
         if (code == 1) {
             console.log(data)
             Object.assign(orderInfo, data)
         } else {
             uni.showToast({
                 mask: true,
                 title: message ?? '请求异常',
                 icon: 'error'
             })
             setTimeout(() => {
                 goBack()
             },800)
         }
     }


     // 支付方式
     const paymentWay = ref('wechat')
     const handlePaymentWayChange = (e) => {
         paymentWay.value = '' + e;
     }

     const handleSelectPayment = (way) => {
         paymentWay.value = way;
     }

     const paymentPop = ref(false)
     const actionPay = () => {
         paymentPop.value = true
     }

     // 发起支付
     const toPay = async () => {
         paymentPop.value = false
         uni.showLoading({
             title: '加载中'
         });
         const { code, data, message } = await initiatePayment({orderId: orderId.value})

         console.log('发起支付', data)
         uni.hideLoading();
         if (code == 1) {
             if (paymentWay.value == 'wechat') {
                 const result =  await payment(data)
                 console.log('发起支付结果',result)
                 // {errMsg: "requestPayment:ok"}
                 if (result?.errMsg && result.errMsg == 'requestPayment:ok') {
                     console.log('支付完成')
                     uni.showToast({
                         mask: true,
                         title: '支付完成',
                         icon: 'success'
                     })
                     await handleGetOrderDetail()
                 }
             } else {
                 uni.showToast({
                     mask: true,
                     title: '支付完成',
                     icon: 'success'
                 })
                 await handleGetOrderDetail()

             }

         } else {
             uni.showModal({
                 title: '提示',
                 content: message ?? "请求异常",
                 showCancel: false,
                 success: function (res) {
                     if (res.confirm) {
                         console.log('用户点击确定');
                     } else if (res.cancel) {
                         console.log('用户点击取消');
                     }
                 }
             });
             return false
         }
     }

     // 取消订单.
     const toCancel = async () => {
         if (!radioValue.value) {
             uni.showToast({
                 mask: true,
                 title: '请选择原因!',
                 icon: 'error'
             })
             return false
         }
         cancelPop.value = false
         uni.showLoading({
             title: '加载中'
         });
         const {code, data, message} = await cancelOrder({orderId: orderId.value, cancelReason: radioValue.value})
         uni.hideLoading();
         if (code == 1) {
             uni.showToast({
                 mask: true,
                 title: '取消完成',
                 icon: 'success'
             })
             await handleGetOrderDetail()
         } else {
             uni.showToast({
                 mask: true,
                 title: message ?? '请求异常',
                 icon: 'error'
             })
         }
     }
 </script>

 <style lang="scss" scoped>
 	.container {
 		padding: 60rpx 26rpx 100rpx;
 	}



 	.item {
 		@include between(100%);
 		position: relative;
 		margin-bottom: 40rpx;
 		padding: 34rpx 38rpx;
 		background: #FFFFFF;
 		border-radius: 30rpx;

 		.icon {
 			position: absolute;
 			top: 0;
 			right: 38rpx;
 			z-index: 9;
 		}

 		.user-info-box {
 			position: relative;
 			@include between(100%);
 			z-index: 99;

 			.status-box {
 				display: flex;
 				align-items: center;
 			}

 			.status {
 				color: #6087EF;
 			}

 			.done {
 				color: #AAAAAA;
 			}
 		}

 		.user-info {
 			@include start();
 			align-items: flex-end;

 			.name {
 				font-size: 32rpx;
 				color: #312C2A;
 			}

 			.age {
 				font-size: 26rpx;
 				color: #606672;
 				margin-left: 26rpx;
 			}

 			.self {
 				@include center(86rpx, 38rpx);
 				margin-left: 30rpx;
 				background: linear-gradient(315deg, #D66A44 0%, #ECBFAF 100%);
 				border-radius: 7rpx;
 				font-size: 26rpx;
 				color: #fff;
 			}
 		}

 		.mobile {
 			margin-top: 38rpx;
 			font-size: 26rpx;
 			color: #606672;
 		}
 	}

 	.order-item {
 		margin-bottom: 30rpx;
 		padding: 38rpx 38rpx 1rpx;
 		background: #FFFFFF;
 		border-radius: 30rpx;

 		.status-box {
 			padding-bottom: 32rpx;
 			border-bottom: 1rpx solid #E8E8E8;
 			margin-bottom: 30rpx;

 			.name {
 				font-size: 30rpx;
 				color: #312C2A;
 			}

 			.status {
 				color: #6087EF;
 			}

 			.status1 {
 				color: #AAAAAA;
 			}
 		}

 		.content-box {
 			width: 100%;
 			position: relative;
 			font-size: 26rpx;
 			color: #606672;

 			.content-item {
 				@include between(100%);
 				margin-bottom: 30rpx;
 				font-size: 26rpx;
 				color: #606672;

 				&>text {
 					&:nth-child(2) {
 						color: #312C2A;
 					}
 				}
 			}

 			.icon {
 				position: absolute;
 				bottom: 0;
 				right: 0;
 				z-index: 99;
 			}
 		}

 		.btns-box {
 			padding-top: 32rpx;
			padding-bottom: 37rpx;
 			border-top: 1rpx solid #E8E8E8;
 			margin-top: 30rpx;
 			@include between(100%);

 			.message {
 				font-size: 26rpx;
 				color: #6087EF;
 			}
 		}
 	}

 	.cancel-pop {
 		padding: 40rpx;
 		background: #FFFFFF;
 		box-shadow: 0rpx 0rpx 30rpx 1rpx rgba(153, 153, 153, 0.16);
 		border-radius: 30rpx 30rpx 0rpx 0rpx;

 		.pop-title {
 			color: #000000;
 			font-size: 32rpx;
 		}

 		.info {
 			margin-top: 14rpx;
 			margin-bottom: 40rpx;
 			background: #F6F6F6;
 			border-radius: 20rpx;
 			padding: 26rpx 30rpx;
 			color: #000000;

 			&>view {
 				margin-bottom: 16rpx;
 			}
 		}
        .radio-wrap {
            margin-top: 36rpx;
        }
        .btn {
            // box-shadow: 0rpx 0rpx 16rpx 1rpx rgba(0,0,0,0.1);
            margin-top: 50rpx;
        }

        .payment-item {
            @include between(100%);
            .left {
                @include start();
                .pay-name {
                    color: #000000;
                    font-size: 28rpx;
                    margin-left: 16rpx;
                }
                .pay-tip {
                    margin-left: 16rpx;
                    color: #B3BCCC;
                }
            }
        }
        .center {
            margin: 20rpx 0;
        }
 	}
 </style>
